﻿using Moven.ViewModels;
using Plugin.Share;
using Xamarin.Forms;
using static Moven.Statics;
using FormsToolkit;
using Moven.Controls;
using Plugin.Share.Abstractions;

namespace Moven.Views
{
    public class ArticleDetailsView : BasePage
    {
        ExtendedToolbarItem _bookmarkButton;
        ArticleWithBookmark _article;

		public ArticleDetailsView (ArticleWithBookmark article)
		{
            BindingContext = _article = article;
            var webView = new WebView
            {
                VerticalOptions = LayoutOptions.FillAndExpand,
                HorizontalOptions = LayoutOptions.FillAndExpand,
                Source = article.Url,
                Margin = new Thickness(8)
            };
            Content = new StackLayout
            {
                BackgroundColor = Color.White,
                Children =
                {
                    webView
                }
            };
			var shareButton = new ExtendedToolbarItem(ToolbarItems)
            {
                Icon = "share.png",
                Text = "分享",
                Command = new Command(_ => CrossShare.Current
				                      .Share(new ShareMessage 
											{ 
												Url = article.Url, 
												Title = "墨文分享", 
												Text = article.Title 
											}))
            };
			_bookmarkButton = new ExtendedToolbarItem(ToolbarItems)
            {
                Command = new Command(() => 
                {
					_article.IsBookmarked = !_article.IsBookmarked;
					SaveArticleBookmarkStatus(_article);

					MessagingService.Current.SendMessage(ArticleChangedMessageId, _article);
                    UpdateBookmarkButtonAndTitle();
                })
            };
			var openInBrowserButton = new ExtendedToolbarItem(ToolbarItems)
			{
				Icon = "open_in_browser.png",
				Text = "在浏览器打开",
				Command = new Command(_ => CrossShare.Current.OpenBrowser(_article.Url, new BrowserOptions
				{
					ChromeShowTitle = true,
					ChromeToolbarColor = new ShareColor { R = 3, G = 169, B = 244, A = 255 },
					UseSafariReaderMode = true,
					UseSafariWebViewController = true
				}))
			};
            UpdateBookmarkButtonAndTitle();
        }

        void UpdateBookmarkButtonAndTitle()
        {
            var isBookmarked = _article.IsBookmarked;
            _bookmarkButton.Icon = isBookmarked ? "bookmarked.png" : "unbookmarked.png";
            _bookmarkButton.Text = isBookmarked ? "收藏" : "不再收藏";
            Title = isBookmarked ? "[已收藏] " + _article.Title : _article.Title; 
        }
	}
}
